/**
 * @author denis.onishchenko@gmail.com
 */

package com.prapp.mediag;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout.LayoutParams;
import android.widget.TextView;

public final class ContactsActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contacts);

        Bundle extras = getIntent().getExtras();
        int tabIndex = extras.getInt(PRApplication.TAB_INDEX);

        PRApplication application = (PRApplication) getApplication();

        Config.ContactsTab contactsTab = (Config.ContactsTab) application.getTab(tabIndex);

        if (contactsTab == null)
            return;

        List<Config.Group> groups = contactsTab.getGroupList();

        if (groups == null)
            return;

        String title = contactsTab.getName();
        if (title != null) {
            TextView textView = (TextView) findViewById(R.id.tvTitle);
            textView.setText(title);
        }

        LinearLayout content = (LinearLayout) findViewById(R.id.llContent);
        content.setBackgroundColor(0xFFDFEFF2);

        for (Config.Group group : groups)
            addGroupView(content, group);
    }

    private void addGroupView(ViewGroup content, Config.Group group) {
        if (group == null) return;

        String name = group.getName();
        if (name != null) {
            TextView textView = new TextView(this);
            textView.setText(name);
            textView.setTextColor(Color.WHITE);
            textView.setShadowLayer(2, 0, 0, Color.BLACK);
            textView.setBackgroundResource(R.drawable.contacts_group_name);
            textView.setPadding(10, 2, 0, 0);
            content.addView(textView, new LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        }

        List<Config.Contact> contacts = group.getContactList();

        if (contacts != null)
            for (Iterator i = contacts.iterator(); i.hasNext(); ) {
                Config.Contact contact = (Config.Contact) i.next();
                addContactView(content, contact);
                if (i.hasNext()) addSeparator(content);
            }
    }

    private void addContactView(ViewGroup content, Config.Contact contact) {
        if (contact == null) return;

        String address = contact.getAddress();
        if (address != null) {
            TextView textView = new TextView(this);
            textView.setGravity(Gravity.CENTER_HORIZONTAL);
            textView.setText(address);
            textView.setTextColor(Color.BLACK);
            textView.setBackgroundResource(R.drawable.contacts_address_background);
            content.addView(textView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        }

        List<Object> list = contact.getList();
        if (list != null)
            for (Object object : list)
                addObjectView(content, object);
    }

    private void addSeparator(ViewGroup content) {
        ImageView image = new ImageView(this);
        image.setImageResource(R.drawable.contacts_separator);
        image.setScaleType(ImageView.ScaleType.FIT_XY);
        content.addView(image, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    }

    private void addObjectView(ViewGroup content, Object object) {
        if (object == null) return;

        if (object instanceof Config.Email)
            addEmailView(content, (Config.Email) object);
        else if (object instanceof Config.Img)
            addImgView(content, (Config.Img) object);
        else if (object instanceof Config.Map)
            addMapView(content, (Config.Map) object);
        else if (object instanceof Config.Phone)
            addPhoneView(content, (Config.Phone) object);
    }

    private void addMapView(ViewGroup content, final Config.Map map) {
        Button button = new Button(this);
        button.setText(map.getText());
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                onMapButtonClick(map);
            }
        });

        LayoutParams layoutParams = new LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(10, 0, 10, 0);
        content.addView(button, layoutParams);
    }

    private void addPhoneView(ViewGroup content, final Config.Phone phone) {
        Button button = new Button(this);
        button.setText(phone.getText());
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                onPhoneButtonClick(phone);
            }
        });

        LayoutParams layoutParams = new LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(10, 0, 10, 0);
        content.addView(button, layoutParams);
    }

    private void addEmailView(ViewGroup content, final Config.Email email) {
        Button button = new Button(this);
        button.setText(email.getText());
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                onEmailButtonClick(email);
            }
        });

        LayoutParams layoutParams = new LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(10, 0, 10, 0);
        content.addView(button, layoutParams);
    }

    private void addImgView(ViewGroup content, Config.Img img) {
        try {
            String src = img.getSrc();

            Bitmap bitmap = createBitmap(src);

            ImageView image = new ImageView(this);
            image.setImageBitmap(bitmap);
            image.setScaleType(ImageView.ScaleType.CENTER);

            LayoutParams layoutParams = new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.gravity = Gravity.CENTER;
            layoutParams.setMargins(10, 10, 10, 10);

            content.addView(image, layoutParams);
        }
        catch (Throwable x) {
            Log.w(getClass().getName() + ".createImgView", "Can't create image", x);
        }
    }

    private Bitmap createBitmap(String path) throws IOException {
        InputStream is = getAssets().open(path.replace("@images/", ""), AssetManager.ACCESS_STREAMING);
        try {
            return BitmapFactory.decodeStream(is);
        }
        finally {
            is.close();
        }
    }

    private void onMapButtonClick(Config.Map map) {
        try {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(map.getUrl())));
        }
        catch (Throwable x) {
            Log.w(getClass().getName() + ".onMapButtonClick", "Can't show map", x);
        }
    }

    private void onPhoneButtonClick(Config.Phone phone) {
        try {
            startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone.getNumber())));
        }
        catch (Throwable x) {
            Log.w(getClass().getName() + ".onPhoneButtonClick", "Can't make call", x);
        }
    }

    private void onEmailButtonClick(Config.Email email) {
        try {
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_EMAIL, new String[] {email.getEmail()});

            startActivity(Intent.createChooser(intent, getString(R.string.SendYourEmailIn)));
        }
        catch (Throwable x) {
            Log.w(getClass().getName() + ".onShareEmail", "Can't share with email", x);
        }
    }
}
